package com.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.ExceptionCodeEnum;
import com.crmeb.core.utils.RedisUtil;
import com.zbkj.crmeb.plat.by.dto.ByCommonConstant;
import com.zbkj.crmeb.store.model.Relation;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.service.CommonStoreOrderService;
import com.zbkj.crmeb.store.service.StoreOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

@Component
@Slf4j
public class PersonPayLimitUtils{

    @Resource
    private RedisUtil redisUtil;
    @Qualifier("directStoreOrderServiceImpl")
    @Autowired
    private CommonStoreOrderService commonStoreOrderService;
    @Resource
    private StoreOrderService storeOrderService;

    private final static String PERSON_LIMIT_KEY = "person_limit:";

    public CommonResult<String> checkPrice(BigDecimal payPrice, String idCard, String idCardName){
//        if (null == payPrice|| StringUtils.isAnyBlank(idCar,idCarName)){
//            return CommonResult.failed("");
//        }
//        relationService.count(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, ByCommonConstant.BY_UP)
//                .eq(Relation::getBusinessType, productRelationsType.getCode()));
//        if (true) return CommonResult.success();
        try {
//            BigDecimal personLimitPrice = getPersonLimitPrice(idCard,idCardName);
            BigDecimal personLimitPrice = new BigDecimal("26000");
            // 根据身份证号查询历史订单
            List<StoreOrder> storeOrders = storeOrderService.list(Wrappers.<StoreOrder>lambdaQuery().eq(StoreOrder::getIdCard, idCard).in(StoreOrder::getStatus, Arrays.asList(1, 2, 6)));
            if (CollectionUtils.isEmpty(storeOrders)){
                // 额度够
                if (personLimitPrice.compareTo(payPrice)>=0){
                    return CommonResult.success(personLimitPrice.toString());
                }
                return CommonResult.failed("个人年度剩余额度不足，支付金额："+payPrice.toString()+",剩余额度："+personLimitPrice.toString());
            }
            BigDecimal totalPayPrice = BigDecimal.ZERO;
            for (StoreOrder storeOrder : storeOrders) {
                totalPayPrice = totalPayPrice.add(storeOrder.getPayPrice());
            }
            if (personLimitPrice.compareTo(totalPayPrice.add(payPrice))>=0){
                return CommonResult.success(personLimitPrice.toString());
            }
            return CommonResult.failed("个人年度剩余额度不足，支付金额："+payPrice.toString()+",剩余额度："+(personLimitPrice.subtract(totalPayPrice)).toString());
        }catch (Exception e){
            log.error("个人额度校验失败: ",e);
        }
        return CommonResult.success("");

    }

    private BigDecimal getPersonLimitPrice(String idCard, String idCardName) {
        String key = PERSON_LIMIT_KEY+idCard;
        Object value = redisUtil.get(key);
        if (value != null && Double.parseDouble(String.valueOf(value))!=0){
            double limitPrice = Double.parseDouble(String.valueOf(value));
            return BigDecimal.valueOf(limitPrice);

        }
        StoreOrder storeOrder = new StoreOrder();
        storeOrder.setPayName(idCardName);
        storeOrder.setIdCard(idCard);
        CommonResult<String> commonResult = commonStoreOrderService.personalQuota(storeOrder);
        if (null == commonResult || !Objects.equals(ExceptionCodeEnum.SUCCESS.getCode(),commonResult.getCode()) || null == commonResult.getData()){
            return BigDecimal.ZERO;
        }
        String dataStr = commonResult.getData();
        JSONObject resultObj = JSON.parseObject(dataStr);
        if (!Objects.equals(resultObj.getString("errorMsg"),"success")){
            return BigDecimal.ZERO;
        }
        JSONObject data = resultObj.getJSONObject("data");
        Double remaining = data.getDouble("remaining");
        redisUtil.set(key,String.valueOf(remaining),60*24L, TimeUnit.MINUTES);
        return BigDecimal.valueOf(remaining);
    }

}
